package com.yanfan.njLighting.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.code.DataType;
import com.serotonin.modbus4j.exception.ErrorResponseException;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.yanfan.common.utils.DateUtils;
import com.yanfan.njLighting.domain.NjLightingDevice;
import com.yanfan.njLighting.domain.NjLightingDeviceStatus;
import com.yanfan.njLighting.service.INjLightingDeviceService;
import com.yanfan.njLighting.service.INjLightingDeviceStatusService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

public class OneOffsetQuery {


    /**
     * 定时智能照明回路状态
     *
     * @throws ModbusTransportException
     * @throws ErrorResponseException
     * @throws ModbusInitException
     */
    public static String getLightingStatus(NjLightingDeviceStatus deviceStatus,String address,int port) throws ModbusInitException {


            ModbusMaster master = null;
            try {
                master = Modbus4jUtils.getMaster(address,port);
            } catch (ModbusInitException e) {
                throw new RuntimeException(e);
            }
            // 定义一个从站 ID 和偏移量的列表
            int dataType = DataType.FOUR_BYTE_INT_UNSIGNED; // 数据类型
            // 获取寄存器偏移量
            String time = DateUtils.getTime();
            NjLightingDeviceStatus status = new NjLightingDeviceStatus();
            try {
                // 单独读取每个寄存器的数据
                Number number = Modbus4jUtils.readHoldingRegister(master,
                        1, Integer.valueOf(deviceStatus.getDeviceOffset()), DataType.TWO_BYTE_INT_UNSIGNED);
                return String.valueOf(number);
            } catch (Exception e) {
                // 单个寄存器读取失败，设置默认值并记录错误
                System.out.println("读取设备 " + " 时发生异常：" + e.getMessage());
            }
            return "获取失败！";
    }
}
